package com.pie4cloud.pie.dmz.server;

import com.pie4cloud.pie.dmz.handler.NettyInitializerFilter;
import com.pie4cloud.pie.dmz.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

@Component
public class NettyServer {
	@Value("${netty.port}")
	private int port;

	@PostConstruct
	public  void nettyServerRun() {
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.localAddress(new InetSocketAddress(port)).childHandler(new NettyInitializerFilter<>(new NettyServerHandler()))
					.option(ChannelOption.SO_BACKLOG, 128)//  Socket参数，服务端接受连接的队列长度，如果队列已满，客户端连接将被拒绝。默认值，Windows为200，其他为128。

					.childOption(ChannelOption.SO_KEEPALIVE, true);//  Socket参数，连接保活，默认值为False。启用该功能时，TCP会主动探测空闲连接的有效性。可以将此功能视为TCP的心跳机制，需要注意的是：默认的心跳间隔是7200s即2小时。Netty默认关闭该功能。

			ChannelFuture future = bootstrap.bind().sync();
			if (future.isSuccess()){
				System.out.println("服务端已成功启动，端口：" + port);
			}
			//future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			//workerGroup.shutdownGracefully();
			//bossGroup.shutdownGracefully();
		}
	}
}
